package com.hhly.rabbitmq.work;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.hhly.rabbitmq.RabbitMQUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class Worker {
	public static void main(String[] args) throws Exception {
		receive("work1");
		//receive("work2");
	}
	public static void  receive(final String name) throws Exception {
		final Channel channel = RabbitMQUtil.getChannel();
		Map<String, Object> map = new HashMap<>();
		map.put("x-max-priority", 10);
		channel.queueDeclarePassive(NewTask.TASK_QUEUE_NAME);
		//channel.queueDeclare(NewTask.TASK_QUEUE_NAME, false, false, false, map);
		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
					byte[] body) throws IOException {
				String message = new String(body, "UTF-8");
				System.out.println(name+"  "+properties.getPriority()+" [x] Received '" + message + "'"+System.currentTimeMillis());
				channel.basicAck(envelope.getDeliveryTag(), false);
			}
		};
		channel.basicConsume(NewTask.TASK_QUEUE_NAME, false, consumer);
		//保证在接收端一个消息没有处理完时不会接收另一个消息，即接收端发送了ack后(或者执行完成)才会接收下一个消息。在这种情况下发送端会尝试把消息发送给下一个not busy的接收端。
		channel.basicQos(1);
	}
}
